package com.demo.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Utility for Strings.
 */
public class Strings {
	public final static String DEFAULT_SEPARATOR = "=";
	public final static String DEFAULT_KEYVALUE_SEPARATOR = ", ";

	/**
	 * Append to a StringBuilder a key/value. Uses default separators.
	 * 
	 * @param sb
	 *            StringBuilder to use
	 * @param key
	 *            Key to append.
	 * @param value
	 *            Value to append.
	 * @return Passed <code>sb</code> populated with key/value.
	 */
	public static StringBuilder appendKeyValue(final StringBuilder sb,
			final String key, final Object value) {
		return appendKeyValue(sb, key, value, DEFAULT_SEPARATOR,
				DEFAULT_KEYVALUE_SEPARATOR);
	}

	/**
	 * Append to a StringBuilder a key/value. Uses default separators.
	 * 
	 * @param sb
	 *            StringBuilder to use
	 * @param key
	 *            Key to append.
	 * @param value
	 *            Value to append.
	 * @param separator
	 *            Value to use between key and value.
	 * @param keyValueSeparator
	 *            Value to use between key/value sets.
	 * @return Passed <code>sb</code> populated with key/value.
	 */
	public static StringBuilder appendKeyValue(final StringBuilder sb,
			final String key, final Object value, final String separator,
			final String keyValueSeparator) {
		if (sb.length() > 0) {
			sb.append(keyValueSeparator);
		}
		return sb.append(key).append(separator).append(value);
	}

	/**
	 * Given a PTR string generated via reverse DNS lookup, return everything
	 * except the trailing period. Example for host.example.com., return
	 * host.example.com
	 * 
	 * @param dnPtr
	 *            a domain name pointer (PTR) string.
	 * @return Sanitized hostname with last period stripped off.
	 *
	 */
	public static String domainNamePointerToHostName(String dnPtr) {
		if (dnPtr == null)
			return null;
		return dnPtr.endsWith(".") ? dnPtr.substring(0, dnPtr.length() - 1)
				: dnPtr;
	}

	/**
	 * 过滤掉特殊字符
	 * 
	 * @param str
	 * @return
	 * @throws PatternSyntaxException
	 */
	public static String stringFilter(String str) throws PatternSyntaxException {
		String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}
}
